package com.banciyuan.bcywebview.biz.pc;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.myinterface.PushActionInterface;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.view.imageview.CircleImageView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.setting.ChangeIntroActivity;
import com.banciyuan.bcywebview.biz.setting.ChangeNickActivity;
import com.banciyuan.bcywebview.biz.setting.SelectCityDialog;
import com.banciyuan.bcywebview.biz.setting.SettingGenderDialog;
import com.banciyuan.bcywebview.biz.write.photoselecotor.pselector.PhotoActivity;
import com.banciyuan.bcywebview.utils.file.ImageManager;
import com.banciyuan.bcywebview.utils.http.NetUtils;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.soundcloud.android.crop.Crop;

import java.io.File;

import de.greenrobot.daoexample.model.MineInfo;

/**
 * Created by hy on 2015/6/11.
 */
public class EditInfoActivity extends BaseActivity implements View.OnClickListener {

    public final static int REQ_PIC = 1;

    private CircleImageView touXiang;
    private TextView tvName;
    private TextView tvGender;
    private TextView tvCity;
    private RequestQueue mQueue;
    private Bitmap successBitmap;
    private PersonHelper mHeadHelper;
    private MineInfo mineInfo;
    private ImageLoader imageLoader;
    private String avatar;
    private String name;
    private String address;
    private String gender;
    private String selfIntro = "";
    private TextView tvIntro;
    public final int CHANGNAME = 4;
    public final int CHANGDESC = 5;
    private ActionbarHelper mActionbarHelper;
    private PushActionInterface mChangeHeadImageInterface;
    private View mActionBarView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editinfo);
        initActionbar();
        initUi();
        initArgs();
        initAction();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
        imageLoader = ImageLoader.getInstance();
        initHeadImage();
        Intent intent = getIntent();
        avatar = intent.getStringExtra("avatar");
        name = intent.getStringExtra("name");
        address = intent.getStringExtra("address");
        gender = intent.getStringExtra("gender");
        selfIntro = intent.getStringExtra("selfIntro");
        processData();
    }

    private void initHeadImage() {
        mChangeHeadImageInterface = new PushActionInterface() {
            @Override
            public void onNetError(String result) {
                MyToast.show(EditInfoActivity.this, getString(R.string.failtouploadavatar));
            }

            @Override
            public void PushSuccess(String result) {
                UserDataHelper.getInstance(EditInfoActivity.this).setAvatar(result);
                BaseObserver.getInstance().notifyWatchers(BaseObserver.USER_DATA_CHANGE_EVENT);
                //todo
                if (null != successBitmap) {
                    touXiang.setImageBitmap(successBitmap);
                }
            }
        };
        mHeadHelper = new PersonHelper(this, mChangeHeadImageInterface);
    }

    @Override
    protected void initProgressbar() {
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.edit_info));
    }

    @Override
    protected void initUi() {
        touXiang = (CircleImageView) findViewById(R.id.civ_touxiang);
        tvName = (TextView) findViewById(R.id.tv_nick);
        tvGender = (TextView) findViewById(R.id.tv_gender);
        tvCity = (TextView) findViewById(R.id.tv_city);
        tvIntro = (TextView) findViewById(R.id.tv_desc);
    }

    private void processData() {
        if (StringUtil.notNullStartWithUrlHead(avatar))
            imageLoader.displayImage(avatar, touXiang, ImageOptions.options);
        tvName.setText(name);

        if ("0".equals(gender)) {
            gender = getString(R.string.female);
        } else {
            gender = getString(R.string.male);
        }
        tvGender.setText(gender);
        if (TextUtils.isEmpty(address) || "null".equals(address)) {
            tvCity.setText(getString(R.string.unkonw_address));
        } else {
            tvCity.setText(address);
        }
        tvIntro.setText(Html.fromHtml(selfIntro));
    }


    @Override
    protected void initAction() {
        findViewById(R.id.rl_touxiang).setOnClickListener(this);
        findViewById(R.id.rl_name).setOnClickListener(this);
        findViewById(R.id.rl_gender).setOnClickListener(this);
        findViewById(R.id.rl_city).setOnClickListener(this);
        findViewById(R.id.rl_intro).setOnClickListener(this);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onNetworkError(String result) {
    }

    @Override
    protected Context getContext() {
        return super.getContext();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_touxiang:
                doChangeHeadImage();
                break;
            case R.id.rl_name:
                doChangeName();
                break;
            case R.id.rl_gender:
                doChangeGender();
                break;
            case R.id.rl_city:
                doChangeCity();
                break;
            case R.id.rl_intro:
                doChangeDesc();
                break;
        }
    }

    private void doChangeDesc() {
        Intent intent = new Intent(EditInfoActivity.this, ChangeIntroActivity.class);
        intent.putExtra("desc", selfIntro);
        startActivityForResult(intent, CHANGDESC);
    }

    private void doChangeCity() {
        SelectCityDialog.Builder builder = new SelectCityDialog.Builder(this);
        SelectCityDialog.Builder.ChangeCityListener changeCityListener = new SelectCityDialog.Builder.ChangeCityListener() {
            @Override
            public void onCityChanged(String newCity, String provincecode, String citycode) {
                tvCity.setText(newCity);
            }
        };
        builder.setChangeCityListener(changeCityListener);
        builder.create().show();
    }

    private void doChangeGender() {
        SettingGenderDialog.Builder builder = new SettingGenderDialog.Builder(this, gender);
        SettingGenderDialog.Builder.ChangeGenderListener changeGenderListener = new SettingGenderDialog.Builder.ChangeGenderListener() {
            @Override
            public void onBoyClicked() {
                gender = getString(R.string.male);
                tvGender.setText(gender);
            }

            @Override
            public void onGirlClicked() {
                gender = getString(R.string.female);
                tvGender.setText(gender);
            }
        };
        builder.setChangeGenderListener(changeGenderListener);
        builder.create().show();
    }

    private void doChangeName() {
        Intent intent = new Intent(EditInfoActivity.this, ChangeNickActivity.class);
        intent.putExtra("name", name);
        startActivityForResult(intent, CHANGNAME);
    }

    private void doChangeHeadImage() {
        Intent intent = new Intent(this, PhotoActivity.class);
        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, true);
        startActivityForResult(intent, REQ_PIC);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) return;
        if (requestCode == REQ_PIC) {
            try {
                String filepath = data.getExtras().getString("path");
                File tempfile = new File(ImageManager.getTemp(EditInfoActivity.this), "bcy_header_temp.jpg");
                File orginFile = new File(filepath);
                Uri tempUri = Uri.fromFile(tempfile);
                Uri orginUri = Uri.fromFile(orginFile);
                Crop.of(orginUri, tempUri).asSquare().start(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == Crop.REQUEST_CROP) {
            handleCrop(resultCode, data);
        } else if (CHANGNAME == requestCode) {
            name = data.getStringExtra("name");
            tvName.setText(name);
        } else if (CHANGDESC == requestCode) {
            selfIntro = data.getStringExtra("intro");
            tvIntro.setText(selfIntro);
        }
    }

    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == RESULT_OK) {
            handlePicResult(Crop.getOutput(result));
        } else if (resultCode == Crop.RESULT_ERROR) {
            MyToast.show(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT);
        }
    }


    public void handlePicResult(Uri uri) {
        if (uri == null) return;

        if (!NetUtils.checkNetwork(this)) {
            MyToast.show(this, getString(R.string.net_check_first));
            return;
        }
        Bitmap bm = BitmapFactory.decodeFile(uri.getPath());
        ImageManager.saveTempImage(EditInfoActivity.this, bm, PersonHelper.FAT, true, PersonHelper.FAT_SIZE, 100);
        ImageManager.saveTempImage(EditInfoActivity.this, bm, PersonHelper.BIG, true, PersonHelper.BIG_SIZE, 90);
        ImageManager.saveTempImage(EditInfoActivity.this, bm, PersonHelper.MIDDLE, true, PersonHelper.MIDDLE_SIZE, 90);
        ImageManager.saveTempImage(EditInfoActivity.this, bm, PersonHelper.SMALL, true, PersonHelper.SMALL_SIZE, 90);
        mHeadHelper.doPush();
        successBitmap = bm;
    }
}
